define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'clothmaking_orders/index' + location.search,
                    add_url: 'clothmaking_orders/add',
                    edit_url: 'clothmaking_orders/edit',
                    del_url: 'clothmaking_orders/del',
                    multi_url: 'clothmaking_orders/multi',
                    import_url: 'clothmaking_orders/import',
                    table: 'clothmaking_orders',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'customer_require', title: __('Customer_require'), operate: 'LIKE'},
                        // {field: 'quantity', title: __('Quantity')},
                        {field: 'limitedDate', title: __('Limiteddate'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'customer_demand_id', title: __('Customer_demand_id')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'img_address', title: __('Img_address'), operate: 'LIKE'},
                        {field: 'pdf_address', title: __('Pdf_address'), operate: 'LIKE'},
                        {field: 'outbound_status', title: __('Outbound_status'), searchList: {"0":"已出库","1":"未出库","2":"部分出库"}, formatter: Table.api.formatter.normal},
                        {field: 'remaining_quantity', title: __('Remaining_quantity'), operate: 'RANGE'},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

        },
        add: function () {
            $("#c-customer_id").data("params", function (obj) {
                $('#c-customer_demand_id').selectPageClear();
            });
            $("#c-customer_demand_id").data("params", function (obj) {
                //obj为SelectPage对象
                return {customer_id: $("#c-customer_id").val()};
            });
            
            Controller.initCustomerDemandTable();

            Controller.api.bindevent();
        },
        edit: function () {
            $("#c-customer_id").data("params", function (obj) {
                $('#c-customer_demand_id').selectPageClear();
            });
            $("#c-customer_demand_id").data("params", function (obj) {
                //obj为SelectPage对象
                return {customer_id: $("#c-customer_id").val()};
            });
            Controller.initCustomerDemandTable();
            
            Controller.api.bindevent();


        },
        initCustomerDemandTable: function() {
            // 客户需求ID变化时加载表格数据
            $("#customer-demand-table").bootstrapTable({
                url: 'customer_demand/getTableData',
                method: 'get',
                queryParams: function(params) {
                    var query = {
                        demand_ids: $("#c-customer_demand_id").val(), 
                    };
                    return query;
                },
                // 列中展示产品ID和产品名称和数量输入框
                columns: [
                    {field: 'demand_id', title: '需求ID'},
                    {field: 'id', title: '产品ID'},
                    {field: 'name', title: '产品名称'},
                    {
                        field: 'quantity',
                        title: '数量',
                        formatter: function(value, row, index) {
                            if ($("#customer_demand_quantity").val() ) {
                                var existingData = JSON.parse($("#customer_demand_quantity").val());
                                var existingEntry = existingData.find(function(entry) {
                                    return entry.demand_id == row.demand_id;
                                });
                                if (existingEntry) {
                                    return '<input type="number" name="customer_demand_quantity_' + row.id + '" class="form-control count-data" value="' + existingEntry.quantity + '" min="0">';
                                }
                            }
                            
                            return '<input type="number" name="customer_demand_quantity_' + row.id + '" class="form-control count-data" value="0" min="0">';
                        }
                    }
                ]
            });
            $(document).on("change", "#c-customer_demand_id", function(){
                $.ajax({
                    url: 'customer_demand/getTableData',
                    method: 'get',
                    dataType: 'json',
                    // 携带请求参数
                    data: {
                        demand_ids: $("#c-customer_demand_id").val(), 
                    },
                    success: function(data) {
                        $("#customer-demand-table").bootstrapTable('load', data['rows']);
                        //清空隐藏字段
                        $("#customer_demand_quantity").val('');
                        $(".count-data").on("change", function() {
                            var currentTableData = Controller.getTableDataWithQuantities();
                            $("#c-customer_demand_quantity").val(JSON.stringify(currentTableData));
                        });
                    }
                });
            });
        },
        getTableDataWithQuantities: function() {
            var tableData = [];
            
            $('#customer-demand-table tbody tr').each(function(index) {
                var row = $(this);
                var rowData = {
                    demand_id: row.find('td:eq(0)').text(), // 第一列：需求ID
                    id: row.find('td:eq(1)').text(), // 第二列：产品ID
                    name: row.find('td:eq(2)').text(), // 第三列：名称
                    quantity: row.find('input[type="number"]').val() // 数量输入框的值
                };
                tableData.push(rowData);
            });
            
            return tableData;
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"),
                );
            }
        }
    };
    return Controller;
});